<?php

namespace app\common\service;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Exception;

class OfficeService
{
    private $spreadsheet;

    private $sheet;

    /**
     * OfficeService constructor.
     */
    public function __construct()
    {
        $this->spreadsheet = new Spreadsheet();
        $this->sheet = $this->spreadsheet->getActiveSheet();
    }

    /**
     * @param array $title
     * @return OfficeService
     * @throws Exception
     */
    public function setTitle($title = [])
    {
        if (!is_array($title)) {
            throw new Exception('请传入数组形式参数');
        }
        foreach ($title as $key => $value) {
            $this->sheet->setCellValue($key, $value);
        }
        return $this;
    }

    /**
     * @param array $data
     * @return $this
     * @throws Exception
     * 传入数据
     */
    public function addExcelData($data = [])
    {
        if (!is_array($data)) {
            throw new Exception('请传入数组形式参数');
        }
        foreach ($data as $vo) {
            foreach ($vo as $voo) {
                $this->sheet->setCellValue($voo['col'], $voo['value']);
            }
        }
        return $this;
    }

    /**
     * @param $filename
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function saveExcel($filename)
    {
        $file = 'filename="' . $filename . '"';
        $writer = new Xlsx($this->spreadsheet);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
        header('Content-Disposition: attachment;' . $file);//告诉浏览器输出浏览器名称
        header('Cache-Control: max-age=0');//禁止缓存
        $writer->save('php://output');
    }

}